﻿using Jupiter.Infrastructure.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Wips.AgentServer.Models;
using Wips.AppService.Publisher.Responses;
using Wips.Infrastructure.Helpers;

namespace Wips.AgentServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AgentController : ControllerBase
    {

        // 健康检查

        [HttpGet("health")]
        public IActionResult Health()
        {
            return Ok("ok");
        }

        /// <summary>
        /// 上传一个文件
        /// </summary>
        /// <param name="upload"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<FileUploadResponse> UploadFile(FileUpload upload)
        {
            var response = new FileUploadResponse();
            if (upload.File.Length > 0)
            {
                if (!upload.File.FileName.ToLower().EndsWith(".zip"))
                {
                    throw new CoreException("暂时只能上传zip文件！");
                }
                var path = ".\\publish\\" + upload.ServerName;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                var newName = DateTime.Now.ToString("yyyyMMddHHmmss") + upload.File.FileName;
                var filePath = Path.Combine(path, newName);

                using (var stream = System.IO.File.Create(filePath))
                {
                    await upload.File.CopyToAsync(stream);
                }
                // 解析一下路径

                response.DirectoryList = ZipHelper.ListZipContents(filePath);
                response.Path = filePath;
                return response;
            }
            throw new CoreException("上传文件失败！");

        }

    }
}
